package com.ruicar.afs.cloud.basic.common.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruicar.afs.cloud.basic.common.entity.BasicSms;
import com.ruicar.afs.cloud.basic.common.mapper.BasicSmsMapper;
import com.ruicar.afs.cloud.basic.common.service.BasicSmsService;
import com.ruicar.afs.cloud.common.core.exception.AfsBaseException;
import com.ruicar.afs.cloud.common.util.EmptyUtils;
import com.ruicar.afs.cloud.message.sendmessage.dto.MessageDataDto;
import com.ruicar.afs.cloud.message.sendmessage.dto.SendMessageDto;
import com.ruicar.afs.cloud.message.sendmessage.dto.SendResultInfoDto;
import com.ruicar.afs.cloud.message.sendmessage.service.MessageService;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: Lee
 * @date 2020-06-16 08:40:39
 * @description
 */
@Service
@AllArgsConstructor
public class BasicSmsServiceImpl extends ServiceImpl<BasicSmsMapper, BasicSms> implements BasicSmsService {
    private final MessageService messageService;
    public static final int TOTAL_NUM = 200;
    //短信
    private final String SHORT_MSG = "short-msg";

    @Override
    @ApiOperation("短信发送")
    public void sendMessage() {
            BasicSms basicSms = new BasicSms();
            basicSms.setTotalNum(TOTAL_NUM);
//            basicSms.setTemplateType(AfsEnumUtil.key(MessageTemplateBusinessEnum.FIRST_REPAYMENT_REMINDER));
            List<BasicSms> list = this.baseMapper.getList(basicSms);
            if (EmptyUtils.isNotEmpty(list)) {
                handleSms(list);
            }
    }

    /**
     * 处理发送短信信息
     *
     * @param list
     */
    public void handleSms(List<BasicSms> list) {
        List<BasicSms> basicSmsList = new ArrayList<>();
        SendMessageDto sendMessageDto =null;
        for (BasicSms basicSms : list) {
            if (sendMessageDto==null) {
                basicSmsList = new ArrayList<>();
                sendMessageDto =convertFrom(basicSms);
                basicSmsList.add(basicSms);
            } else {
                if (sendMessageDto.getChannel().equals(basicSms.getChannel()) && sendMessageDto.getCode().equals(basicSms.getCode()) && sendMessageDto.getUid().equals(basicSms.getUid())) {
                    basicSmsList.add(basicSms);
                } else {
                    sendSms(sendMessageDto, basicSmsList);
                    basicSmsList = new ArrayList<>();
                    sendMessageDto =convertFrom(basicSms);
                    basicSmsList.add(basicSms);
                }
            }
        }
        if(EmptyUtils.isNotEmpty(basicSmsList)) {
            sendSms(sendMessageDto, basicSmsList);
        }
    }
    /**
     * 组装数据
     *
     * @param list
     * @return
     */
    public List<MessageDataDto> getList(List<BasicSms> list) {
        List<MessageDataDto> messageDataDtos = list.stream().map(basicSms -> {
            MessageDataDto dataDto = new MessageDataDto();
            BeanUtil.copyProperties(basicSms, dataDto);
            //短信参数
            dataDto.setSummaryId(basicSms.getContractNo() + basicSms.getPriority() + basicSms.getSmsContent() + DateUtil.format(new Date(), "yyyyMMdd"));
            return dataDto;
        }).collect(Collectors.toList());
        return messageDataDtos;
    }

    /**
     * 发送短信
     * @param messageDto
     * @param list
     */
    private void sendSms(SendMessageDto messageDto, List<BasicSms> list) {
        messageDto.setMessageDataDto(getList(list));
        //发送接口
        SendResultInfoDto sendResultInfoDto = messageService.sendMessageData(messageDto);
        //失败抛异常
        if ("false".equals(sendResultInfoDto.getResult())) {
            throw new AfsBaseException(MessageFormat.format("响应码说明:{0}", sendResultInfoDto.getMsgInfo()));
        }
        if (CollectionUtil.isNotEmpty(list)) {
            this.removeByIds(list.stream().map(sms -> Convert.toStr(sms.getId())).collect(Collectors.toList()));
        }
    }

    public static SendMessageDto convertFrom(BasicSms basicSms){
        SendMessageDto sendMessageDto = new SendMessageDto();
        sendMessageDto.setChannel(basicSms.getChannel());
        sendMessageDto.setCode(basicSms.getCode());
        sendMessageDto.setUid(basicSms.getUid());
        sendMessageDto.setTimestamp(System.currentTimeMillis() / 1000 + "");
        return sendMessageDto;
    }
}
